package sprintServer.doing.thread;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;

import sprintServer.model.FriendModel;
import sprintServer.model.Protocal;
import sprintServer.start.FriendInfo;
import sprintServer.start.LoginStateUdpdate;
import sprintServer.start.LogoutClient;
import sprintServer.start.MassgeUpdate;
import sprintServer.start.SerchFriend;
import sprintServer.start.ServerJoin;
import sprintServer.start.ServerLogin;
import sprintServer.start.SprintServer;

public class SprintServerThread implements Runnable {

	private Socket socket;
	private SprintServer ss;
	BufferedReader br;
	BufferedWriter bw;
	InputStream is;
	InputStreamReader isr;
	OutputStream os;
	OutputStreamWriter osw;
	private String clientId;

	public String getClientId() {
		return clientId;
	}
	public SprintServerThread(SprintServer ss){
		this.ss = ss;
	}
	@Override
	public synchronized void run() {
		// TODO Auto-generated method stub
		boolean isStop = false;
		
		try{
		
			socket = ss.getSocket();
			System.out.println("info : "+socket.getInetAddress());
			is = socket.getInputStream();
			isr = new InputStreamReader(is);
			br = new BufferedReader(isr);
			os = socket.getOutputStream();
			osw = new OutputStreamWriter(os);
			bw = new BufferedWriter(osw);

			while(!isStop){

				System.out.println("서버대기중...");
				String mes= br.readLine();
				System.out.println("클라이언트 Tr : "+mes);

				String [] tr = mes.split(":");
				int check =Integer.parseInt(tr[1]);
				System.out.println("tr 숫자 : "+tr.length);
				System.out.println("프로토콜 정보 : "+check);

				if(check==Protocal.login){
					System.out.println("로그인 처리 진입");
					String id = tr[3];
					clientId = id;
					String pass = tr[5];
					ServerLogin sl = new ServerLogin();
					String result = sl.login(id,pass);
					if(result.equals("success")){
						LoginStateUdpdate lsu = new LoginStateUdpdate();
						String result2 = lsu.loginStateUpdate(id);
						if(result2.equals("success")){
							FriendInfo friendInfo = new FriendInfo();
							ArrayList<FriendModel> fm = friendInfo.getFriend(id);		
							ArrayList<SprintServerThread> s = ss.getSstList(); 
							String  tran = "Protocal:"+Protocal.loginSucces ; 
							for (int f=0;f<fm.size();f++){ 
								FriendModel myfriend = fm.get(f);
								tran+=":friend"+f+":"+myfriend.getFriendName()+":friend"+f+"state:"+myfriend.getFriendState();
							}					

							sending(tran); 

							String friendTran = "Protocal:"+Protocal.friend+":ID:"+id; 

							for(int fr=0;fr<fm.size();fr++){
								FriendModel myfriend = fm.get(fr);
								if(myfriend.getFriendState()==1){
									for(int sf=0; sf<s.size();sf++){
										SprintServerThread imsi = s.get(sf);
										if(myfriend.getFriendName().trim().equals(imsi.clientId.trim())){
											imsi.sendingFriend(friendTran);
										}
									}
								}

							}
							sendingFriend(friendTran);

						}else{
							String  tran = "Protocal:"+Protocal.loginfalse ;
							sending(tran);
						}
					}else{
						String  tran = "Protocal:"+Protocal.loginfalse ;
						sending(tran);
					}
							
				}else if(check==Protocal.join){
					System.out.println("가입 처리 진입");

					String id = tr[3];
					clientId = id;
					String pass = tr[5];
					ServerJoin sj = new ServerJoin();
					String result = sj.join(id,pass);
					System.out.println("db 처리 결과 : "+result);
					if(result.equals("succes")){
						String  tran = "Protocal:"+Protocal.joinSucces ;
						sending(tran);
					}else{
						String  tran = "Protocal:"+Protocal.joinfalse ;
						sending(tran);
					}
				}else if(check==Protocal.logout){
					System.out.println("로그아웃 처리 진입");
					String id = tr[4];
					String pass = tr[6];
					LogoutClient logoutClient = new LogoutClient();
					String result = logoutClient.logout(id,pass);
					if(result.equals("success")){
						String  tran = "Protocal:"+Protocal.logout ;
						sending(tran);
						isStop = true;
						ss.getSstList().remove(this);

					}else{

						String  tran = "Protocal:"+Protocal.logoutfalse ;
						sending(tran);

					}
				}else if(check==Protocal.sendMassge){
					System.out.println("메시지전송 처리 진입");
					String id = tr[3];
					clientId = id;
					String message = tr[7];
					String tgId = tr[5];
					boolean result = sendMassge(tgId,mes);
					MassgeUpdate mu = new MassgeUpdate();
					int su = mu.massgeUp(id,message,tgId,result);	
					if(su == 0){
						System.out.println("로그인 에러");
						
					}
				}else if(check==Protocal.serch){
					String id = tr[3];
					SerchFriend sf = new SerchFriend();
					String result = sf.serchFriend(id);
					String  tran = "Protocal:"+Protocal.serchResult+":Result"+result;
					sending(tran);
				}
			
			}
		}catch(Exception e){
			System.out.println("에러 발생 :"+e.toString());
			ss.getSstList().remove(this);
		}
		
	}
	private boolean sendMassge(String tgid,String tr) {
		// TODO Auto-generated method stub
		boolean reCheck = false;
		ArrayList<SprintServerThread> s = ss.getSstList();
		for(int i=0; i<s.size();i++){
			SprintServerThread check = s.get(i);
			if(tgid == check.clientId){
				try{
					check.sending(tr);
					reCheck = true;
				}catch(IOException ad){}
			}
		}
		
		return reCheck;
	}
	private void sendingFriend(String tr)throws IOException {
		// TODO Auto-generated method stub

		bw.write(tr+"\n");
		bw.flush();
		System.out.println("서버 Tr : "+tr);
		
	}
	private void sending(String tr)throws IOException {
		// TODO Auto-generated method stub

		bw.write(tr+"\n");
		bw.flush();
		System.out.println("서버 Tr : "+tr);
		
	}

}
